package org.java.user.web;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.alibaba.druid.util.StringUtils;
import org.java.entity.User;
import org.java.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.yaml.snakeyaml.emitter.Emitable;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author WHQ
 * @version 1.0
 * @date 2022-3-10 0010 下午 2:27
 */
@Controller
public class UserController {
    @Resource
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static String imgCodePrefix="imgCodePrefix:";
    @Value("${email.code.prefix}")
    private String prefix;
    /**
     * 访问地址:http://api.shopping.com/user/getCode
     * 生成随机验证码的方法
     * @param response
     */
    @GetMapping("/getCode")
    public void getCode(HttpServletResponse response, HttpServletRequest request){
        String remoteAddr = request.getRemoteAddr();
        //拼接存入redis中的键
        String key=imgCodePrefix+remoteAddr;
        // 随机生成 4 位验证码
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        //设置图片验证码的大小
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 50);
        //得到验证码
        String code = lineCaptcha.getCode();
        //将验证码存放到redis中，过期时间3分钟
        stringRedisTemplate.boundValueOps(key).set(code);
        //设置超时时间
        stringRedisTemplate.expire(key,2, TimeUnit.MINUTES);
        System.out.println("存入redis成功");
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        try {
            // 调用父类的 setGenerator() 方法，设置验证码的类型
            lineCaptcha.setGenerator(randomGenerator);
            // 输出到页面
            lineCaptcha.write(response.getOutputStream());
            // 打印日志
            System.out.println("随机生成的验证码:"+code);
            // 关闭流
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 访问地址:http://api.shopping.com/user/check/code
     * @param code
     * @return
     */
    @PostMapping("/check/code/{code}")
    public ResponseEntity<Boolean> checkCode(@PathVariable("code")String code,HttpServletRequest request){
        String remoteAddr = request.getRemoteAddr();
        //拼接存入redis中的键
        String key=imgCodePrefix+remoteAddr;
        System.out.println("进入验证码图片验证码的方法");
        //从redis中取出图片验证码
        String redisCode = stringRedisTemplate.boundValueOps(key).get();
        if (StringUtils.equals(code,redisCode)){
            //相等，验证通过
            return ResponseEntity.ok(true);
        }else {
            //不相等，验证失败
            return ResponseEntity.ok(false);
        }
    }
    /**
     * 访问地址:http://api.shopping.com/user/check/email/code/{code}
     * @param code
     * @return
     */
    @PostMapping("/check/email/code/{code}/{email}")
    public ResponseEntity<Boolean> checkEmailCode(@PathVariable("code")String code,@PathVariable("email")String email,HttpServletRequest request){
        //拼接key
        String key=prefix+email;
        //从redis中取出邮箱验证码
        String emailCode = stringRedisTemplate.boundValueOps(key).get();
        if (StringUtils.equals(code,emailCode)) {
            //验证通过
            return ResponseEntity.ok(true);
        }else {
            //验证失败
            return ResponseEntity.badRequest().body(false);
        }
    }
    /**
     * 访问地址:http://api.shopping.com/user/checkUserId
     * @param
     * @return
     */
    @PostMapping("/checkUserId")
    public ResponseEntity<Boolean> checkUserId(@Valid User user){
        System.out.println(user.getEmail());
        System.out.println("进入验证用户名的方法");
        Boolean flag=userService.checkUserId(user);
        System.out.println(flag);
        if (flag){
            System.out.println("用户名存在");
            //用户存在
            return ResponseEntity.badRequest().body(false);
        }
        System.out.println(1);
        //用户名不存在，可以正常注册
        return ResponseEntity.ok(true);
    }

    /**
     * 访问地址:http://api.shopping.com/user/send/email
     * @param to
     * @return
     */
    @PostMapping("/send/email/{to}")
    public ResponseEntity<Boolean> sendEmail(@PathVariable("to") String to){
        System.out.println(to);
        userService.sendToMq(to);
        return ResponseEntity.ok(true);
    }

    /**
     * 访问地址:http://api.shopping.com/user/register
     * @param user
     * @return
     */
    @PostMapping("/register")
    public ResponseEntity<Boolean> register(@Valid User user){
        System.out.println(user.getEmail());
        Boolean flag=userService.register(user);
        if (flag){
            //注册成功
            return ResponseEntity.ok(true);
        }else {
            //注册失败
            return ResponseEntity.badRequest().body(false);
        }
    }

    /**
     * 访问地址:http://api.shopping.com/user/query
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/query")
    public ResponseEntity<User> queryUser(@RequestParam("username")String username,
                                            @RequestParam("password")String password){
        System.out.println(username+password);
        //通过账号密码查询用户信息
        User user=userService.queryUser(username,password);
        if (user!=null){
            //查询成功，返回用户信息
            return ResponseEntity.ok(user);
        }else {
            //查询失败，返回错误
            return ResponseEntity.badRequest().build();
        }
    }
}
